import SwiftUI
import Combine
 
class SearchViewModel: ObservableObject {
    @Published var searchText = ""
    @Published var results: [String] = []
 
    private var cancellables = Set<AnyCancellable>()
 
    init() {
        $searchText
            .debounce(for: .milliseconds(1000), scheduler: RunLoop.main)
            .removeDuplicates()
            .sink { [weak self] text in
                self?.search(text)
            }
            .store(in: &cancellables)
    }
 
    func search(_ query: String) {
        guard !query.isEmpty else {
            results = []
            return
        }
        // 模拟结果
        results = ["\(query) - 1", "\(query) - 2", "\(query) - 3"]
    }
}
 
struct DemoSearchView: View {
    @StateObject var vm = SearchViewModel()
 
    var body: some View {
        VStack {
            TextField("搜索", text: $vm.searchText)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
 
            List(vm.results, id: \.self) { result in
                Text(result)
            }
        }
    }
}




class TextViewModel: ObservableObject {
    @Published var inputText: String = ""
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        $inputText
            .sink { text in
                NSLog("%@", "你输入了：\(text)")
            }
            .store(in: &cancellables)
    }
}


struct TextInputView: View {
    @StateObject var vm = TextViewModel()
    
    var body: some View {
        TextField("输入点什么", text: $vm.inputText)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()
    }
}



#Preview {
    
//    DemoSearchView(vm: SearchViewModel())
    TextInputView()
    
    
}
